#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <cstring>
#include <iostream>
using namespace std;


enum CMD{
	CMD_LOGIN,
	CMD_LOGIN_RESULT,
	CMD_LOGOUT,
	CMD_LOGOUT_RESULT,
	CMD_ERROR
};

struct DataHeader
{
	short datalength;
	short cmd;
};


struct Login:public DataHeader
{
	Login(){
		datalength=sizeof(Login);
		cmd=CMD_LOGIN;
	}
	char userName[32];
	char password[32];
};
struct LoginResult:public DataHeader
{
	LoginResult(){
		datalength=sizeof(LoginResult);
		cmd=CMD_LOGIN_RESULT;
		result=1;
	}
	int result;
};

struct Logout:public DataHeader
{
	Logout(){
		datalength=sizeof(Logout);
		cmd=CMD_LOGOUT;
	}
	char userName[32];
};
struct LogoutResult:public DataHeader
{
	LogoutResult(){
		datalength=sizeof(LogoutResult);
		cmd=CMD_LOGOUT_RESULT;
		result=1;
	}
	int result;
};

int main(){
    //创建套接字
    int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if(sock==-1)
    {
        cout<<"Socket build failed."<<endl;
    }
    else
    {
        cout<<"Socket build success."<<endl;
    }

    //向服务器（特定的IP和端口）发起请求
    struct sockaddr_in serv_addr;
    memset(&serv_addr, 0, sizeof(serv_addr));  //每个字节都用0填充
    serv_addr.sin_family = AF_INET;  //使用IPv4地址
    serv_addr.sin_addr.s_addr = inet_addr("192.168.30.128");  //具体的IP地址
    serv_addr.sin_port = htons(1234);  //端口
    int cRes=connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
    if(cRes==-1)
	{
		cout<<"Client failed to connect server."<<endl;
	}
    else
	{
		cout<<"client has successfully connected to the server."<<endl;
	}

    while(true){
        string s;
        cout<<"Input data to send:";
        getline(cin,s);
        write(sock,(char*)s.c_str(),s.length());
		if(0 == strcmp("exit", s.c_str())){
			
			cout << "Client exit." << endl;
			break;
		}
        else if (0 == strcmp("login", s.c_str())) {
            Login login;
            strcpy(login.userName,"zjl");
            strcpy(login.password,"zjlpw");
            send(sock,(char *)&login,sizeof(Login),0);
            LoginResult loginResult = {};
            recv(sock,(char *)&loginResult,sizeof(LoginResult),0);
			cout << endl << "Login result is " << loginResult.result << endl;
        }
        else if (0 == strcmp("logout", s.c_str())) {
			Logout logout;
            strcpy(logout.userName,"zjl");
            send(sock,(char *)&logout,sizeof(Logout),0);
            LogoutResult logoutResult = {};
            recv(sock,(char *)&logoutResult,sizeof(LogoutResult),0);
			cout << endl << "Logout result is " << logoutResult.result<< endl;
		}
        else{
			cout << "Client wrong input, please input again." << endl;
		}
    }

    //关闭套接字
    close(sock);
    return 0;
}

